"use client"

import type React from "react"
import { useState, useRef, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { CalendarIcon, Save, Upload, FileText, ImageIcon, Archive, X, Download, Trash2, Loader2 } from "lucide-react"
import { format } from "date-fns"
import { zhCN } from "date-fns/locale"
import { cn } from "@/lib/utils"
import { DataType, CreateDataRequest, DataRecord, CollectionMethod } from "@/types/taskdata"
import { Project } from "@/types/project"
import { useProjects } from "@/hooks/project"

// 表单数据接口
interface FormData {
  project_id: string
  name: string
  description: string
  type: DataType
  location: string
  collection_date: string
  crop_type: string
  collection_method: CollectionMethod
  customCrop?: string
}

// 组件props接口
interface DataCollectionProps {
  onDataSubmit?: (data: any) => void
  recentRecords?: DataRecord[]
  dataTypeStats?: Array<{ type: string; count: number; color: string }>
}

const DataCollection: React.FC<DataCollectionProps> = ({ 
  onDataSubmit, 
  recentRecords = [], 
  dataTypeStats = [] 
}) => {
  const { projects, fetchProjects } = useProjects()
  
  const [formData, setFormData] = useState<FormData>({
    project_id: "",
    name: "",
    description: "",
    type: "sensor",
    location: "",
    collection_date: "",
    crop_type: "",
    collection_method: "manual"
  })

  const [date, setDate] = useState<Date | undefined>()
  const [uploadedFiles, setUploadedFiles] = useState<File[]>([])
  const [isDragOver, setIsDragOver] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  
  // 文件操作状态管理
  const [fileMessage, setFileMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)
  const [processingFiles, setProcessingFiles] = useState<Set<string>>(new Set())

  // 初始化加载项目列表
  useEffect(() => {
    fetchProjects()
  }, [])

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 处理表单字段变化
  const handleInputChange = (field: keyof FormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
  }

  // 处理日期变化
  const handleDateChange = (selectedDate: Date | undefined) => {
    setDate(selectedDate)
    if (selectedDate) {
      setFormData(prev => ({
        ...prev,
        collection_date: format(selectedDate, "yyyy-MM-dd")
      }))
    }
  }

  // 文件上传处理
  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || [])
    setUploadedFiles(prev => [...prev, ...files])
  }

  const handleUploadAreaClick = () => {
    fileInputRef.current?.click()
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragOver(true)
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragOver(false)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragOver(false)
    const files = Array.from(e.dataTransfer.files)
    setUploadedFiles(prev => [...prev, ...files])
  }

  const removeFile = (index: number) => {
    setUploadedFiles(prev => prev.filter((_, i) => i !== index))
  }

  const getFileIcon = (file: File) => {
    const extension = file.name.split('.').pop()?.toLowerCase()
    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(extension || '')) {
      return <ImageIcon className="h-4 w-4 text-blue-500 flex-shrink-0" />
    }
    if (['zip', 'rar', '7z'].includes(extension || '')) {
      return <Archive className="h-4 w-4 text-green-500 flex-shrink-0" />
    }
    return <FileText className="h-4 w-4 text-purple-500 flex-shrink-0" />
  }

  // 提交表单
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    try {
      const requestData: CreateDataRequest = {
        project_id: formData.project_id || "",
        name: formData.name,
        description: formData.description,
        type: formData.type,
        location: formData.location,
        collection_date: formData.collection_date,
        crop_type: formData.crop_type === "other" ? formData.customCrop : formData.crop_type,
        attachments: uploadedFiles
      }
      
      // 调用父组件的回调函数（如果存在）
      if (onDataSubmit) {
        const submitData = {
          experimentName: formData.name,
          cropType: formData.crop_type === "other" ? (formData.customCrop || "other") : formData.crop_type,
          customCrop: formData.customCrop,
          collector: "current-user", // 可以从上下文获取实际用户
          location: formData.location,
          date: formData.collection_date,
          temperature: "", // 新的表单中没有这些字段，设为空
          humidity: "",
          soilMoisture: "",
          lightIntensity: "",
          notes: formData.description,
          files: uploadedFiles
        }
        onDataSubmit(submitData)
      }
      
      console.log('提交数据:', requestData)
      alert('数据保存成功！')
      resetForm()
    } catch (error) {
      console.error('保存数据失败:', error)
      alert('保存数据失败，请重试')
    }
  }

  // 重置表单
  const resetForm = () => {
    setFormData({
      project_id: "",
      name: "",
      description: "",
      type: "sensor",
      location: "",
      collection_date: "",
      crop_type: "",
      collection_method: "manual"
    })
    setDate(undefined)
    setUploadedFiles([])
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  return (
    <div className="w-full max-w-7xl space-y-6">
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <Card>
            <CardHeader>
              <CardTitle>农业数据采集</CardTitle>
              <CardDescription>请填写完整的农业观测数据信息</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="name">
                      数据名称 <span className="text-red-500">*</span>
                    </Label>
                    <Input
                      id="name"
                      value={formData.name}
                      onChange={(e) => handleInputChange("name", e.target.value)}
                      placeholder="输入数据记录名称"
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="type">
                      数据类型 <span className="text-red-500">*</span>
                    </Label>
                    <Select
                      value={formData.type}
                      onValueChange={(value: DataType) => handleInputChange("type", value)}
                      required
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择数据类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="spectral">光谱数据</SelectItem>
                        <SelectItem value="image">图像数据</SelectItem>
                        <SelectItem value="sensor">传感器数据</SelectItem>
                        <SelectItem value="weather">气象数据</SelectItem>
                        <SelectItem value="soil">土壤数据</SelectItem>
                        <SelectItem value="disease">病虫害数据</SelectItem>
                        <SelectItem value="yield">产量数据</SelectItem>
                        <SelectItem value="others">其他数据</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="collection_method">
                      采集方式 <span className="text-red-500">*</span>
                    </Label>
                    <Select
                      value={formData.collection_method}
                      onValueChange={(value: CollectionMethod) => handleInputChange("collection_method", value)}
                      required
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择采集方式" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="manual">手动采集</SelectItem>
                        <SelectItem value="automatic">自动采集</SelectItem>
                        <SelectItem value="sensor">传感器采集</SelectItem>
                        <SelectItem value="remote">远程采集</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="project_id">
                      关联项目
                    </Label>
                    <Select
                      value={formData.project_id || "none"}
                      onValueChange={(value) => handleInputChange("project_id", value === "none" ? "" : value)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择项目（可选）" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">无关联项目</SelectItem>
                        {Array.isArray(projects) && projects.map((project) => (
                          <SelectItem key={project.id} value={project.id}>
                            {project.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description">
                    数据描述 <span className="text-red-500">*</span>
                  </Label>
                  <Textarea
                    id="description"
                    value={formData.description}
                    onChange={(e) => handleInputChange("description", e.target.value)}
                    placeholder="详细描述数据内容、采集目的和相关信息..."
                    rows={3}
                    required
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="cropType">
                      作物类型
                    </Label>
                    <div className="flex gap-2">
                      <Select
                        value={formData.crop_type}
                        onValueChange={(value) => handleInputChange("crop_type", value)}
                      >
                        <SelectTrigger className={formData.crop_type === "other" ? "flex-1" : "w-full"}>
                          <SelectValue placeholder="选择作物类型" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="corn">玉米</SelectItem>
                          <SelectItem value="wheat">小麦</SelectItem>
                          <SelectItem value="rice">水稻</SelectItem>
                          <SelectItem value="soybean">大豆</SelectItem>
                          <SelectItem value="potato">马铃薯</SelectItem>
                          <SelectItem value="tomato">番茄</SelectItem>
                          <SelectItem value="other">其他</SelectItem>
                        </SelectContent>
                      </Select>
                      {formData.crop_type === "other" && (
                        <Input
                          id="customCrop"
                          value={formData.customCrop || ""}
                          onChange={(e) => handleInputChange("customCrop", e.target.value)}
                          placeholder="输入作物名称"
                          className="flex-1"
                        />
                      )}
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>
                      采集日期 <span className="text-red-500">*</span>
                    </Label>
                    <Popover>
                      <PopoverTrigger asChild>
                        <Button
                          type="button"
                          variant="outline"
                          className={cn(
                            "w-full justify-start text-left font-normal",
                            !date && "text-muted-foreground",
                          )}
                        >
                          <CalendarIcon className="mr-2 h-4 w-4" />
                          {date ? format(date, "PPP", { locale: zhCN }) : "选择采集日期"}
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0">
                        <Calendar mode="single" selected={date} onSelect={handleDateChange} initialFocus />
                      </PopoverContent>
                    </Popover>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="location">
                      采集地点 <span className="text-red-500">*</span>
                    </Label>
                    <Input
                      id="location"
                      value={formData.location}
                      onChange={(e) => handleInputChange("location", e.target.value)}
                      placeholder="如：试验田A区、温室1号"
                      required
                    />
                  </div>
                </div>

                {/* 附件管理区域 */}
                <div className="border rounded-lg p-4 space-y-4 bg-purple-50/30">
                  <h3 className="font-semibold text-lg mb-4 flex items-center ">
                    <Upload className="w-5 h-5 mr-2" />
                    数据文件上传
                  </h3>
                  
                  {/* 文件操作消息 */}
                  {fileMessage && (
                    <div className={`p-3 rounded-lg ${
                      fileMessage.type === 'success' 
                        ? 'bg-green-50 border border-green-200 text-green-700' 
                        : 'bg-red-50 border border-red-200 text-red-700'
                    }`}>
                      <p className="text-sm">{fileMessage.text}</p>
                    </div>
                  )}
                  
                  <div>
                    <Label htmlFor="fileUpload">上传数据文件</Label>
                    <div className="mt-2">
                      <input
                        ref={fileInputRef}
                        type="file"
                        multiple
                        accept=".zip,.xlsx,.xls,.csv,.jpg,.jpeg,.png,.gif,.webp,.txt,.dat,.json,.pdf,.doc,.docx"
                        onChange={handleFileUpload}
                        className="hidden"
                        id="fileUpload"
                      />
                      <div
                        className={cn(
                          "border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors",
                          isDragOver ? "border-blue-400 bg-blue-50" : "border-gray-300 hover:border-blue-400 hover:bg-blue-50/30",
                        )}
                        onDragOver={handleDragOver}
                        onDragLeave={handleDragLeave}
                        onDrop={handleDrop}
                        onClick={handleUploadAreaClick}
                      >
                        <Upload className="h-8 w-8 mx-auto mb-2 text-gray-400" />
                        <p className="text-sm text-gray-600 mb-2">拖拽文件到此处或点击选择文件</p>
                        <p className="text-xs text-gray-500">支持上传光谱文件、图像、传感器数据、Excel表格等</p>
                      </div>
                    </div>
                  </div>

                  {/* 已选择的文件列表 */}
                  {uploadedFiles.length > 0 && (
                    <div>
                      <Label className="flex items-center">
                        <FileText className="w-4 h-4 mr-1" />
                        待上传的文件 ({uploadedFiles.length})
                      </Label>
                      <div className="mt-3 space-y-2 max-h-60 overflow-y-auto border rounded p-2 bg-white">
                        {uploadedFiles.map((file, index) => (
                          <div key={index} className="flex items-center justify-between p-3 border rounded hover:bg-gray-50">
                            <div className="flex items-center flex-1 min-w-0">
                              {getFileIcon(file)}
                              <div className="flex-1 min-w-0 ml-3">
                                <p className="text-sm font-medium truncate" title={file.name}>{file.name}</p>
                                <p className="text-xs text-gray-500">
                                  {formatFileSize(file.size)}
                                </p>
                              </div>
                            </div>
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              onClick={() => removeFile(index)}
                              className="text-red-500 hover:text-red-700 hover:bg-red-50 h-8 w-8 p-0 flex-shrink-0"
                              title="删除文件"
                            >
                              <X className="w-4 h-4" />
                            </Button>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>

                {/* 提交按钮 */}
                <div className="flex justify-end space-x-2 pt-4">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    重置表单
                  </Button>
                  <Button type="submit" className="flex items-center">
                    <Save className="h-4 w-4 mr-2" />
                    保存数据记录
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </div>

        <div className="space-y-6">
          {recentRecords.length > 0 ? (
            <Card>
              <CardHeader>
                <CardTitle>最近数据记录</CardTitle>
                <CardDescription>最新的农业数据采集活动</CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                {recentRecords.slice(0, 4).map((record, index) => {
                  const getTypeLabel = (type: DataType) => {
                    const typeMap: Record<DataType, string> = {
                      spectral: "光谱",
                      image: "图像", 
                      sensor: "传感器",
                      weather: "气象",
                      soil: "土壤",
                      disease: "病害",
                      yield: "产量",
                      others: "其他"
                    }
                    return typeMap[type] || "未知"
                  }

                  const getTimeAgo = (createdAt: string) => {
                    const now = new Date()
                    const created = new Date(createdAt)
                    const diffMs = now.getTime() - created.getTime()
                    const diffMins = Math.floor(diffMs / (1000 * 60))
                    const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
                    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

                    if (diffMins < 60) {
                      return `${diffMins}分钟前`
                    } else if (diffHours < 24) {
                      return `${diffHours}小时前`
                    } else {
                      return `${diffDays}天前`
                    }
                  }

                  return (
                    <div key={record.id} className="flex items-center justify-between text-sm">
                      <div className="flex-1 min-w-0">
                        <p className="font-medium truncate">{record.name}</p>
                        <div className="flex items-center gap-2 mt-1">
                          <Badge variant="outline" className="text-xs">
                            {getTypeLabel(record.type)}
                          </Badge>
                          <span className="text-muted-foreground text-xs">
                            {getTimeAgo(record.created_at)}
                          </span>
                        </div>
                      </div>
                      <Badge className="text-xs">
                        已保存
                      </Badge>
                    </div>
                  )
                })}
              </CardContent>
            </Card>
          ) : (
            <Card>
              <CardHeader>
                <CardTitle>最近数据记录</CardTitle>
                <CardDescription>最新的农业数据采集活动</CardDescription>
              </CardHeader>
              <CardContent className="text-center py-8">
                <p className="text-muted-foreground">暂无数据记录，请先创建数据记录</p>
              </CardContent>
            </Card>
          )}

          {dataTypeStats.length > 0 ? (
            <Card>
              <CardHeader>
                <CardTitle>数据类型分布</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                {dataTypeStats.map((item, index) => (
                  <div key={index} className="flex items-center justify-between text-sm">
                    <div className="flex items-center gap-2">
                      <div className={`w-3 h-3 rounded ${item.color}`}></div>
                      <span>{item.type}</span>
                    </div>
                    <Badge variant="outline">{item.count}</Badge>
                  </div>
                ))}
              </CardContent>
            </Card>
          ) : (
            <Card>
              <CardHeader>
                <CardTitle>数据类型分布</CardTitle>
              </CardHeader>
              <CardContent className="text-center py-8">
                <p className="text-muted-foreground">暂无数据统计</p>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  )
}

export default DataCollection